/**
 * 获取oss上传配置
 * @returns {any}
 */
export function getPolicy() {
  let policy = JSON.parse(window.sessionStorage.getItem('ossPolicy'))
  let now = Math.floor(Date.parse(new Date()) / 1000)
  // 判断Policy是否失效
  if (policy.expire == undefined || now >= policy.expire) {
    let xmlhttp = null
    if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest()
    } else if (window.ActiveXObject) {
      xmlhttp = new ActiveXObject('Microsoft.XMLHTTP')
    }
    if (xmlhttp != null) {
      xmlhttp.open('GET', '/admin/upload/policy', false)
      xmlhttp.send(null)
      let res = eval('(' + xmlhttp.responseText + ')')
      window.sessionStorage.setItem('ossPolicy', JSON.stringify(res.data))
      policy = res.data
    } else {
      alert('Your browser does not support XMLHTTP.')
      policy = {}
    }
  }
  return policy
}

/**
 * uuid
 * @returns {string}
 */
export function uuid() {
  let d = new Date().getTime()
  if (window.performance && typeof window.performance.now === 'function') {
    d += performance.now() //use high-precision timer if available
  }
  return 'xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    let r = (d + Math.random() * 16) % 16 | 0
    d = Math.floor(d / 16)
    return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16)
  })
}

/**
 * 重命名文件
 * @param filename
 * @returns {string}
 */
export function fileRename(filename) {
  return uuid() + suffix(filename)
}

/**
 * 文件后缀名
 * @param filename
 * @returns {string}
 */
export function suffix(filename) {
  let pos = filename.lastIndexOf('.'),
    suffix = ''
  if (pos != -1) {
    suffix = filename.substring(pos)
  }
  return suffix
}

/**
 *
 * @param {*} key
 */
export function getConfig(file, key) {
  let keysAry = key.split('.')
  let c = require('@/config/' + file + '.js')
  for (let k in keysAry) {
    c = c[keysAry[k]]
  }
  return c != undefined ? c : null
}
export function getValueByKey(keyName, keyValue, arr) {
  for (let i in arr) {
    if (arr[i][keyName] == keyValue) {
      return arr[i]
    }
  }
}
/**
 * 获取get请求参数
 * @param {*} paraName
 * @param {*} url
 */
export function getUrlParam(paraName, url) {
  let arrObj = url.split('?')

  if (arrObj.length > 1) {
    let arrPara = arrObj[1].split('&')
    let arr

    for (let i = 0; i < arrPara.length; i++) {
      arr = arrPara[i].split('=')

      if (arr != null && arr[0] == paraName) {
        return arr[1]
      }
    }
    return ''
  } else {
    return ''
  }
}

/**
 * 递归查数组
 * @param {} value
 * @param {*} key
 * @param {*} array
 */
export function arrayFind(value, key, arr, childKey) {
  for (let i in arr) {
    let item = arr[i]

    if (item[key] == value) {
      console.log(item[childKey], item)
      return item[childKey]
    } else {
      if (item[childKey]) {
        return arrayFind(value, key, item[childKey], childKey)
      } else {
        return []
      }
    }
  }
}
